import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  login:false,
  profile:{},
  isPlay:false,
  currentMusic: '',
  playlist:[],
  recentPlay:[],
  currentMusicIndex:0,
  currentMUsicDuration:0,
  currentPlayListId:0,
  currentMusicId:null,
  currentMusicProgress:0
}

export default new Vuex.Store({
  state,
  mutations:{
    Login(state){
      state.login = true
    },
    ChangeProfile(state,data){
      state.profile = data
    },
    changeCurrentMusic(state,data){
      state.currentMusic = data
    },
    changePlayState(state,isplay){
      state.isPlay = isplay
    },
    addPlayList(state,data){
      state.playlist = data
      state.currentMusicIndex = 0
    },
    addMusic(state,data){
      let index = state.playlist.findIndex(value=>value.name === data.name)
      if(index === -1){
        state.playlist.splice(state.currentMusicIndex+1,0,data)
        if(state.playlist.length > 1){
          state.currentMusicIndex ++
        }
      }else{
        state.currentMusicIndex = index
      }
      localStorage.setItem('currentIndex',state.currentMusicIndex)
    },
    changeCurrentMusicIndex(state,direction){
      if(direction === '0'){
        state.currentMusicIndex++
      }else if(direction === '1'){
        state.currentMusicIndex--
      }else if(direction === '-1'){
        state.currentMusicIndex = 0
      }else{
        state.currentMusicIndex = direction
      }
      if(state.currentMusicIndex >= state.playlist.length || state.currentMusicIndex<0){
        state.currentMusicIndex = 0
      }
      localStorage.setItem('currentIndex',state.currentMusicIndex)
    },
    removePlayList(state){
      state.playlist = []
      state.currentMusicIndex = 0
      state.currentMusic = ''
    },
    changeCurrentDuration(state,data){
      state.currentMUsicDuration = data
    },
    changePlayListId(state,data){
      state.currentPlayListId = data
    },
    changeCurrentMusicProgress(state,data){
      state.currentMusicProgress = data
    },
    changeCurrentMusicId(state,id){
      state.currentMusicId = id
    },
    addRecentPlay(state,data){
      if(!state.recentPlay.includes(data)){
        state.recentPlay.unshift(data)
      }
      if(state.recentPlay.length > 100){
        state.recentPlay.splice(100,1)
      }
      localStorage.setItem('recentPlay',JSON.stringify(state.recentPlay))
    }
  },
  actions: {
  },
  modules: {
  },
  getters:{
    getPlayState(state){
      return state.isPlay
    },
    getCurrentMusicDetail(state){
      return state.playlist[state.currentMusicIndex]
    },
    getCurrentMusicId(state){
      if(state.playlist && state.playlist != []){
        return ''
      }else{
        return state.playlist[state.currentMusicIndex].id
      }
    },
    getCurrentProfileId(state){
      return state.profile.profile.userId
    }
  }
})
